﻿// Copyright (c) Inossem. All rights reserved.
// Licensed under the LGPL-3.0 license. See LICENSE file in the project root for full license information.
using DWF.Studio.Custom;
using DWF.Studio.Host;
using DWF.Studio.ISerivces;
using DWF.Studio.Models;
using DWF.Studio.NuGetManagement;
using DWF.Studio.Project.Build;
using DWF.Studio.Services;
using DWF.Studio.Share.Serialization;
using DWF.Studio.Share.Utils;
using System;
using System.Activities.Expressions;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.IO.Packaging;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Xml.Linq;

namespace DWF.Studio.Project
{
    /// <summary>
    /// 工程管理类
    /// </summary>
    internal class ProjectManager
    {
        private IConfigService _configService = null;

        private IProjectParamDetailSerivce _projectParamDetailSerivce = null;
        /// <summary>
        /// 工程管理实例
        /// </summary>
        private static readonly ProjectManager _projectManager = new ProjectManager();

        /// <summary>
        /// 工程管理类引用
        /// </summary>
        public static ProjectManager Instance
        {
            get
            {
                return _projectManager;
            }
        }

        /// <summary>
        /// 当前打开的工程
        /// </summary>
        public ProjectInfo CurrentProject
        {
            get;
            private set;
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        private ProjectManager()
        {
            _configService = new ConfigService();
            _projectParamDetailSerivce = new ProjectParamDetailSerivce();
        }

        /// <summary>
        /// 创建工程
        /// </summary>
        /// <param name="projectPath"></param>
        /// <param name="XamlFileTemplate"></param>
        /// <returns></returns>
        public ProjectInfo CreateProject(string projectPath, string projectDescription, string projectPlatform, string projectWFLanguage, string XamlFileTemplate)
        {
            var folderExisting = FileHelper.CheckFolderExisting(projectPath);
            if (!folderExisting)
            {
                FileHelper.CreateFolder(projectPath);
            }

            var projectFile = Path.Combine(projectPath, StaticResource.ProjectFile);
            var startFile = Path.Combine(projectPath, StaticResource.ProjectSelfFile, StaticResource.ProjectStart);
            var templatepath = Path.Combine(getAppRootPath(), XamlFileTemplate);

            FileHelper.CreateFolder(Path.Combine(projectPath, StaticResource.ProjectSelfFile));
            FileHelper.CreateFolder(Path.Combine(projectPath, StaticResource.ProjectSelfLibs));
            FileHelper.CreateFolder(Path.Combine(projectPath, StaticResource.ProjectSelfImages));
            FileHelper.CreateFolder(Path.Combine(projectPath, StaticResource.ProjectSelfRes));

            FileHelper.CopyFileToFile(templatepath, startFile);

            ProjectDetail detail = new ProjectDetail();

            var dependencies = _configService.GetProjectDependencies();
            foreach (string key in dependencies)
            {
                detail.dependency.Add(String.Format("id={0};version={1};targetFramework={2}", key, dependencies[key], StaticResource.TargetFramework));
            }

            detail.id = Guid.NewGuid().ToString("N");
            detail.name = Path.GetFileName(projectPath);
            detail.description = projectDescription;
            detail.ver = "1.0.2";
            detail.reversion = "1";
            detail.platform = projectPlatform;
            detail.wflanguage = projectWFLanguage;
            detail.start = StaticResource.ProjectStart;
            detail.file.Add(StaticResource.ProjectStart);

            YamlHelper.Save(detail, projectFile);
            CurrentProject = detail.ConvertToProjectInfo(projectPath);

            return CurrentProject;
        }

        /// <summary>
        /// 加载工程
        /// </summary>
        /// <param name="projectPath"></param>
        /// <returns></returns>
        public ProjectInfo LoadProject(string projectFile)
        {
            var fileExisting = FileHelper.CheckFileExisting(projectFile);
            if (!fileExisting)
            {
                return null;
            }

            var detail = YamlHelper.Load<ProjectDetail>(projectFile);

            if (String.IsNullOrWhiteSpace(detail.platform))//2020.07.09 andy 添加 兼容老版本
            {
                detail.platform = StaticResource.TargetPlatform_x86;
                YamlHelper.Save(detail, projectFile);
            }

            if (String.IsNullOrWhiteSpace(detail.wflanguage))//2020.11.27 andy 添加 兼容老版本
            {
                detail.wflanguage = StaticResource.WorkflowLanguage_vb;
                YamlHelper.Save(detail, projectFile);
            }

            var projectPath = Path.GetDirectoryName(projectFile);
            CurrentProject = detail.ConvertToProjectInfo(projectPath);

            return CurrentProject;
        }

        /// <summary>
        /// 卸载工程
        /// </summary>
        public void UnloadProject()
        {
            CurrentProject = null;
        }

        /// <summary>
        /// 保存工程
        /// </summary>
        private void saveProject()
        {
            var detail = this.CurrentProject.ConvertToDetail();

            var path = System.IO.Path.Combine(CurrentProject.FullName, StaticResource.ProjectFile);
            var oldPath = System.IO.Path.Combine(CurrentProject.FullName, StaticResource.OldProjectFile);
            var projectpath = "";
            if (FileHelper.CheckFileExisting(path))
            {
                projectpath = Path.Combine(CurrentProject.FullName, StaticResource.ProjectFile);
            }
            else if (FileHelper.CheckFileExisting(oldPath))
            {
                projectpath = Path.Combine(CurrentProject.FullName, StaticResource.OldProjectFile);
            }
            YamlHelper.Save(detail, projectpath);
        }

        public Dictionary<string, string> GetProjectProperties()
        {
            Dictionary<string, string> properties = null;
            if (CurrentProject != null)
            {
                properties = new Dictionary<string, string>();

                properties["projectId"] = CurrentProject.Id;
                properties["projectDirectory"] = CurrentProject.FullName;
                properties["projectVersion"] = CurrentProject.ProjectVersion;
                properties["projectWFLanguage"] = CurrentProject.WFLanguage;
                properties["projectTargetPlatform"] = CurrentProject.TargetPlatform;

                properties["projectName"] = CurrentProject.Name;  //Oliver 2021-06-21 for 运行启动参数

                var sysConfig = _configService.LoadSysConfig();
                properties["assetsUri"] = sysConfig.AssetsUri;
            }

            return properties;
        }

        /// <summary>
        /// 重命名工程节点
        /// </summary>
        /// <param name="node"></param>
        /// <param name="newName"></param>
        public bool RenameNode(ProjectNode node, string newName)
        {
            var result = false;
            if (node.NodeType == EProjectNodeType.Project)
            {
            }
            else if (node.NodeType == EProjectNodeType.Folder)
            {
            }
            else if (node.NodeType == EProjectNodeType.File)
            {
                var isExist = node.Parent.Children.Any(item => item.Name == newName);
                if (isExist)
                {
                    return result;
                }

                FileHelper.RenameFile(node.FullName, newName);

                node.DisplayName = newName;
                node.Name = newName;
                node.FullName = Path.Combine(Path.GetDirectoryName(node.FullName), newName);

                this.saveProject();
                result = true;
            }

            return result;
        }

        /// <summary>
        /// 删除工程节点
        /// </summary>
        /// <param name="node"></param>
        public bool DeleteNode(ProjectNode node)
        {
            var result = false;
            if (node.NodeType == EProjectNodeType.Project)
            {
            }
            else if (node.NodeType == EProjectNodeType.Folder)
            {
            }
            else if (node.NodeType == EProjectNodeType.File)
            {
                node.Parent.Children.Remove(node);
                FileHelper.DeleteFile(node.FullName);

                this.saveProject();
                result = true;
            }

            return result;
        }

        /// <summary>
        /// 获取依赖活动包信息
        /// </summary>
        /// <returns></returns>
        public List<PackageInfo> GetDependOnPackageInfos()
        {
            List<PackageInfo> list = null;
            if (CurrentProject != null)
            {
                var dependonPackages = CurrentProject.Children.FirstOrDefault(item => item.NodeType == EProjectNodeType.Dependencies);
                var packages = dependonPackages.Children.Select(item => item as ProjectPackage);

                list = new List<PackageInfo>();
                foreach (var package in packages)
                {
                    list.Add(new PackageInfo() { Id = package.Id, Version = package.Version, TargetFramework = package.TargetFramework, IsInstalled = package.IsExisting, IconUri = package.IconLoc });
                }
            }

            return list;
        }

        /// <summary>
        /// 创建xaml文件
        /// </summary>
        /// <param name="parentNode"></param>
        /// <param name="fileName"></param>
        /// <param name="fileTemplate"></param>
        /// <returns></returns>
        public ProjectFile CreateXamlFileToProject(ProjectNode parentNode, string fileName, string fileTemplate)
        {
            if (parentNode.IsSelf && parentNode.Name == StaticResource.ProjectSelfFile)
            {
                var ext = System.IO.Path.GetExtension(fileName);
                if (String.IsNullOrWhiteSpace(ext) || ext != StaticResource.XamlExtension)
                {
                    fileName += StaticResource.XamlExtension;
                }
            }

            if (parentNode.Children.Any(item => item.Name.ToLower() == fileName.ToLower()))
            {
                return null;
            }

            return addScriptNode(parentNode, fileName, fileTemplate);
        }

        /// <summary>
        /// 安装依赖活动包(最新的)
        /// </summary>
        /// <param name="id"></param>
        /// <param name="version"></param>
        /// <returns></returns>
        public async Task<bool> InstallPackage(string id,bool isDelay=false)
        {
            var issuccess = false;
            if (CurrentProject != null)
            {
                var config = _configService.LoadSysConfig();
                var packageManager = new PackageManager(config.GetStablePackageUri());
                var getPackages = await packageManager.GetPackagesWithAllVersionAsync(id, isDelay);
                if (getPackages!=null)
                {
                    getPackages = getPackages.OrderByDescending(g => g.Version).ToList();
                    var baseDirectory = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory).Parent.FullName;
                    var installPath = Path.Combine(baseDirectory, StaticResource.Activities);//安装路径
                    if (getPackages.Count>0)
                    {
                        var nugetPackage = await packageManager.GetPackageByIdAsync(id, getPackages[0].Version);//获取要安装的活动包
                        if (nugetPackage != null)
                        {
                            var packageDependencies = await packageManager.InstallPackageAsync(nugetPackage, installPath);//安装活动包
                            var dependenciesNode = CurrentProject.Children.FirstOrDefault(item => item.NodeType == EProjectNodeType.Dependencies);//获取工程工依赖节点
                            addDependencyNode(dependenciesNode, id, getPackages[0].Version);//添加活动包
                            foreach (var packageDependency in packageDependencies)//添加活动包的依赖包
                            {
                                addDependencyNode(dependenciesNode, packageDependency.Id, packageDependency.Version, false);
                            }

                            this.saveProject();
                            issuccess = true;
                        }
                    }
                }
            }
            return issuccess;
        }
        /// <summary>
        /// 安装依赖活动包
        /// </summary>
        /// <param name="id"></param>
        /// <param name="version"></param>
        /// <returns></returns>
        public async Task<bool> InstallPackage(string id, string version)
        {
            var issuccess = false;
            if (CurrentProject != null)
            {
                var config = _configService.LoadSysConfig();
                var packageManager = new PackageManager(config.GetStablePackageUri());

                var baseDirectory = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory).Parent.FullName;
                var installPath = Path.Combine(baseDirectory, StaticResource.Activities);//安装路径
                var nugetPackage = await packageManager.GetPackageByIdAsync(id, version);//获取要安装的活动包
                if (nugetPackage != null)
                {
                    var packageDependencies = await packageManager.InstallPackageAsync(nugetPackage, installPath);//安装活动包
                    var dependenciesNode = CurrentProject.Children.FirstOrDefault(item => item.NodeType == EProjectNodeType.Dependencies);//获取工程工依赖节点
                    addDependencyNode(dependenciesNode, id, version);//添加活动包
                    foreach (var packageDependency in packageDependencies)//添加活动包的依赖包
                    {
                        addDependencyNode(dependenciesNode, packageDependency.Id, packageDependency.Version, false);
                    }

                    this.saveProject();
                    issuccess = true;
                }
            }
            return issuccess;
        }

        /// <summary>
        /// 更新依赖活动包
        /// </summary>
        /// <param name="id"></param>
        /// <param name="version"></param>
        /// <param name="newVersion"></param>
        /// <returns></returns>
        public async Task<bool> UpdatePackage(string id, string version, string newVersion)
        {
            var issuccess = false;
            if (CurrentProject != null)
            {
                var config = _configService.LoadSysConfig();
                var packageManager = new PackageManager(config.GetStablePackageUri(), GetPackageStatus.allPackageSource);
                var baseDirectory = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory).Parent.FullName;
                var installPath = Path.Combine(baseDirectory, StaticResource.Activities);//安装路径 
                var nugetPackage = await packageManager.GetPackageByIdAsync(id, newVersion);//获取nuget包信息
                if (nugetPackage != null)
                {
                    var packageDependencies = await packageManager.InstallPackageAsync(nugetPackage, installPath);//安装活动包
                    var dependenciesNode = CurrentProject.Children.FirstOrDefault(item => item.NodeType == EProjectNodeType.Dependencies);//添加活动包的依赖包
                    addDependencyNode(dependenciesNode, id, newVersion);//添加活动包
                    foreach (var packageDependency in packageDependencies)//添加活动包的依赖包
                    {
                        addDependencyNode(dependenciesNode, packageDependency.Id, packageDependency.Version, false);
                    }

                    this.saveProject();
                    issuccess = true;
                }
            }

            return issuccess;
        }

        /// <summary>
        /// 添加活动包节点
        /// </summary>
        /// <param name="dependonPackages"></param>
        /// <param name="id"></param>
        /// <param name="version"></param>
        /// <param name="ignoreVersion"></param>
        private void addDependencyNode(ProjectNode dependonPackages, string id, string version, bool ignoreVersion = true)
        {
            var packageNode = dependonPackages.Children.Select(item => item as ProjectPackage).FirstOrDefault(item => item.Id == id);//查找相同id的包

            if (packageNode == null)//没有则直接添加
            {
                packageNode = new ProjectPackage()
                {
                    Id = id,
                    Version = version,
                    TargetFramework = StaticResource.TargetFramework,
                    Name = id,
                    DisplayName = $"{id}-{version}",
                    FullName = String.Format("id={0};version={1};targetFramework={2}", id, version, StaticResource.TargetFramework),
                    Parent = dependonPackages,
                    IsExisting = true
                };

                dependonPackages.Children.Add(packageNode);
            }
            else //项目已经引用活动包
            {
                if (!ignoreVersion)//是否忽略版本比较
                {
                    var ver1 = Version.Parse(packageNode.Version);
                    var ver2 = Version.Parse(version);
                    if (ver1 > ver2)//如果当前版本大于目标版 忽略安装
                    {
                        return;
                    }
                }

                packageNode.DisplayName = $"{id}-{version}";
                packageNode.Version = version;
                packageNode.FullName = String.Format("id={0};version={1};targetFramework={2}", id, version, StaticResource.TargetFramework);
                packageNode.IsExisting = true;
            }
        }

        /// <summary>
        /// 卸载活动包
        /// </summary>
        /// <param name="id"></param>
        /// <param name="version"></param>
        /// <returns></returns>
        public async Task<bool> UninstallPackage(string id, string version) //当前设计并未物理删除，只是去除了和工程的相关引用
        {
            var issuccess = false;
            if (CurrentProject != null)
            {
                var dependenciesNode = CurrentProject.Children.FirstOrDefault(item => item.NodeType == EProjectNodeType.Dependencies);
                var package = dependenciesNode.Children.Select(item => item as ProjectPackage).FirstOrDefault(item => item.Id == id && item.Version == version);
                dependenciesNode.Children.Remove(package);

                this.saveProject();
                issuccess = true;
            }

            await Task.Yield();

            return issuccess;
        }
        /// <summary>
        /// 批量修改包状态   20200509    Carl
        /// </summary>
        /// <param name="id"></param>
        /// <param name="version"></param>
        /// <returns></returns>
        public async Task<List<NugetPackageWrap>> BatchOperationlPackage(List<NugetPackageWrap> _currentPackageWrapList) //当前设计并未物理删除，只是去除了和工程的相关引用
        {
            List<NugetPackageWrap> errorOperationPackage = new List<NugetPackageWrap>();
            try
            {
                if (CurrentProject != null)
                {
                    List<NugetPackageWrap> currentOperationPackage = new List<NugetPackageWrap>();
                    var dependenciesNode = CurrentProject.Children.FirstOrDefault(item => item.NodeType == EProjectNodeType.Dependencies);
                    int PackageCount = _currentPackageWrapList.Count;
                    for (int i = 0; i < PackageCount; i++)
                    {
                        Views.WindowLoading.SetMsg(_currentPackageWrapList[i].Id);
                        if (_currentPackageWrapList[i].PackageOperationType == PackageOperationType.Install)//安装
                        {
                            var config = _configService.LoadSysConfig();
                            var packageManager = new PackageManager(config.GetStablePackageUri());
                            var baseDirectory = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory).Parent.FullName;
                            var installPath = Path.Combine(baseDirectory, StaticResource.Activities);//安装路径
                            var nugetPackage = await packageManager.GetPackageByIdAsync(_currentPackageWrapList[i].Id, _currentPackageWrapList[i].Version);//获取要安装的活动包
                            if (nugetPackage != null)
                            {
                                var packageDependencies = await packageManager.InstallPackageAsync(nugetPackage, installPath);//安装活动包
                                addDependencyNode(dependenciesNode, _currentPackageWrapList[i].Id, _currentPackageWrapList[i].Version);//添加活动包
                                foreach (var packageDependency in packageDependencies)//添加活动包的依赖包
                                {
                                    addDependencyNode(dependenciesNode, packageDependency.Id, packageDependency.Version, false);
                                }
                            }
                            currentOperationPackage.Add(_currentPackageWrapList[i]);
                        }
                        else if (_currentPackageWrapList[i].PackageOperationType == PackageOperationType.UnInstall)//删除
                        {
                            var package = dependenciesNode.Children.Select(item => item as ProjectPackage).FirstOrDefault(item => item.Id == _currentPackageWrapList[i].Id && item.Version == _currentPackageWrapList[i].Version);
                            dependenciesNode.Children.Remove(package);

                            await Task.Yield();
                            currentOperationPackage.Add(_currentPackageWrapList[i]);
                        }
                        else//更新
                        {
                            var config = _configService.LoadSysConfig();
                            var packageManager = new PackageManager(config.GetStablePackageUri());
                            var baseDirectory = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory).Parent.FullName;
                            var installPath = Path.Combine(baseDirectory, StaticResource.Activities);//安装路径 
                            var nugetPackage = await packageManager.GetPackageByIdAsync(_currentPackageWrapList[i].Id, _currentPackageWrapList[i].Version);//获取nuget包信息
                            if (nugetPackage != null)
                            {
                                var packageDependencies = await packageManager.InstallPackageAsync(nugetPackage, installPath);//安装活动包

                                addDependencyNode(dependenciesNode, _currentPackageWrapList[i].Id, _currentPackageWrapList[i].Version);//添加活动包
                                foreach (var packageDependency in packageDependencies)//添加活动包的依赖包
                                {
                                    addDependencyNode(dependenciesNode, packageDependency.Id, packageDependency.Version, false);
                                }
                            }
                            currentOperationPackage.Add(_currentPackageWrapList[i]);
                        }
                    }
                    this.saveProject();
                    errorOperationPackage = _currentPackageWrapList.Except(currentOperationPackage).ToList();
                }
                return errorOperationPackage;
            }
            catch (Exception e)
            {
                Share.Log.LogHelper.Error(e.ToString());
                return _currentPackageWrapList;
            }
        }
        /// <summary>
        /// 添加脚本节点
        /// </summary>
        /// <param name="parentNode"></param>
        /// <param name="fileName"></param>
        /// <param name="fileTemplate"></param>
        /// <returns></returns>
        private ProjectFile addScriptNode(ProjectNode parentNode, string fileName, string fileTemplate)
        {
            var templatepath = Path.Combine(getAppRootPath(), fileTemplate);
            var fullpath = Path.Combine(parentNode.FullName, fileName);
            FileHelper.CopyFileToFile(templatepath, fullpath);

            ProjectFile file = new ProjectFile()
            {
                Name = fileName,
                DisplayName = fileName,
                FullName = fullpath,
                Parent = parentNode,
                IsExisting = true,
            };

            parentNode.Children.Add(file);

            this.saveProject();

            return file;
        }

        /// <summary>
        /// 拷贝文件
        /// </summary>
        /// <param name="parentNode"></param>
        /// <param name="sourceFile"></param>
        public ProjectFile CopyFileToProject(ProjectNode parentNode, string sourceFile)
        {
            var fileName = Path.GetFileName(sourceFile);
            var fullPath = Path.Combine(parentNode.FullName, fileName);
            if (parentNode.Children.Any(item => item.Name.ToLower() == fileName.ToLower()))
            {
                return null;
            }

            FileHelper.CopyFileToFile(sourceFile, fullPath);

            ProjectFile file = new ProjectFile()
            {
                Name = fileName,
                DisplayName = fileName,
                FullName = fullPath,
                Parent = parentNode,
                IsExisting = true,
            };

            parentNode.Children.Add(file);

            this.saveProject();

            return file;
        }
        /// <summary>
        /// 保存到片段文件
        /// </summary>
        /// <param name="parentNode"></param>
        /// <param name="sourceFile"></param>
        public bool SaveToSnippet(ProjectNode parentNode,string targetFolder)
        {
            var validata = ValidateScriptALL(parentNode.FullName);
            if (validata.Count() > 0)
                return false;
            if (!FileHelper.CheckFolderExisting(targetFolder))
            {
                FileHelper.CreateFolder(targetFolder);
            }
            FileHelper.CopyFileToFolder(parentNode.FullName, targetFolder);

            return true;
        }
        private string getAppRootPath()
        {
            return AppDomain.CurrentDomain.BaseDirectory;
        }

        /// <summary>
        /// 生成工程
        /// </summary>
        /// <param name="targetPath"></param>
        public string BuidProject(string targetPath, string version, string description, string procName = null, bool isCustomContent = false, bool containPackages = true, bool allowParallel = false, bool requireAdmin = false, List<ProjectTreeView> projectFolders = null, bool isApplication = false)
        {
            if (CurrentProject == null)
            {
                return null;
            }

            CurrentProject.ProjectVersion = version;
            ProjectBuilder projectBuilder = new ProjectBuilder(CurrentProject);
            projectBuilder.SetProcessAllowParallel(allowParallel)
                .SetProcessRequireAdmin(requireAdmin)
                .SetProcessContainPackages(containPackages)
                .SetProcessReversion(version)
                .SetProcessDescription(description);
            _projectParamDetailSerivce = new ProjectParamDetailSerivce();
            var projectParam = _projectParamDetailSerivce.GetProjectParamDetail();
            List<Build.ProjectParam> inputParams = new List<Build.ProjectParam>();
            foreach (var item in projectParam.Input)
            {
                inputParams.Add(new Build.ProjectParam()
                {
                    name = item.Name,
                    paramType = (EProjectParamType)item.ParamType,
                    description = item.Description,
                    value = item.Value
                });
            }
            List<Build.ProjectParam> outputParams = new List<Build.ProjectParam>();
            foreach (var item in projectParam.Output)
            {
                outputParams.Add(new Build.ProjectParam()
                {
                    name = item.Name,
                    paramType = (EProjectParamType)item.ParamType,
                    description = item.Description,
                    value = item.Value
                });
            }
            projectBuilder.SetProcessInputParam(inputParams).SetProcessOutputParam(outputParams);

            return projectBuilder.Build(targetPath, procName, isCustomContent, projectFolders, isApplication);
        }

        /// <summary>
        /// 刷新资源文件夹
        /// </summary>
        public void RefreshResFolder()
        {
            if (CurrentProject != null)
            {
                var resFolder = CurrentProject.Children.FirstOrDefault(item => item.NodeType == EProjectNodeType.Folder && item.Name == StaticResource.ProjectSelfRes);
                if (resFolder != null)
                {
                    var path = resFolder.FullName;
                    string[] fullNames = Directory.GetFiles(path);

                    foreach (var filefullname in fullNames)
                    {
                        var fileName = Path.GetFileName(filefullname);

                        var isExist = resFolder.Children.Any(item => item.Name == fileName);
                        if (!isExist)
                        {
                            ProjectFile file = new ProjectFile();

                            file.Name = fileName;
                            file.DisplayName = fileName;
                            file.FullName = filefullname;
                            file.Parent = resFolder;
                            file.IsExisting = FileHelper.CheckFileExisting(filefullname);
                            resFolder.Children.Add(file);
                        }
                    }

                    this.saveProject();
                }
            }
        }

        /// <summary>
        /// 刷新图像文件夹
        /// </summary>
        public void RefreshImageFolder(List<string> imagesList = null)
        {
            if (CurrentProject != null)
            {
                var imageFolder = CurrentProject.Children.FirstOrDefault(item => item.NodeType == EProjectNodeType.Folder && item.Name == StaticResource.ProjectSelfImages);
                if (imageFolder != null)
                {
                    var path = imageFolder.FullName;
                    string[] fullNames = Directory.GetFiles(path);
                    if (imagesList == null)
                    {
                        foreach (var filefullname in fullNames)
                        {
                            var fileName = Path.GetFileName(filefullname);

                            var isExist = imageFolder.Children.Any(item => item.Name == fileName);
                            if (!isExist)
                            {
                                ProjectFile file = new ProjectFile();

                                file.Name = fileName;
                                file.DisplayName = fileName;
                                file.FullName = filefullname;
                                file.Parent = imageFolder;
                                file.IsExisting = FileHelper.CheckFileExisting(filefullname);
                                imageFolder.Children.Add(file);
                            }
                        }
                    }
                    else
                    {
                        imageFolder.Children.Clear();
                        foreach (var fileName in imagesList)
                        {
                            var filefullname = System.IO.Path.Combine(CurrentProject.FullName, StaticResource.ProjectSelfImages) + "\\" + fileName;

                            var isExist = imageFolder.Children.Any(item => item.Name == fileName);
                            if (!isExist)
                            {
                                ProjectFile file = new ProjectFile();

                                file.Name = fileName;
                                file.DisplayName = fileName;
                                file.FullName = filefullname;
                                file.Parent = imageFolder;
                                file.IsExisting = FileHelper.CheckFileExisting(filefullname);
                                imageFolder.Children.Add(file);
                            }
                        }
                    }

                    this.saveProject();
                }
            }
        }

        /// <summary>
        /// 获取项目文件
        /// </summary>
        /// <param name="fullName"></param>
        /// <returns></returns>
        public ProjectFile GetProjectFile(string fullName)
        {
            ProjectFile result = null;

            if (CurrentProject != null)
            {
                var node = recursiveNode(CurrentProject.Children.ToList(), fullName);
                result = node as ProjectFile;
            }

            return result;
        }

        public ProjectFolder GetProjectFolder(string folderName)
        {
            ProjectFolder result = null;

            if (CurrentProject != null)
            {
                result = CurrentProject.Children.FirstOrDefault(item => item.Name == folderName) as ProjectFolder;
            }

            return result;
        }

        private ProjectNode recursiveNode(List<ProjectNode> nodes, string fullName)
        {
            ProjectNode result = null;

            foreach (var node in nodes)
            {
                if (node.FullName == fullName)
                {
                    result = node;
                    break;
                }

                if (node.NodeType == EProjectNodeType.Folder)
                {
                    result = recursiveNode(node.Children.ToList(), fullName);
                    if (result != null)
                    {
                        break;
                    }
                }
            }

            return result;
        }

        /// <summary>
        /// 更改项目名称
        /// </summary>
        /// <param name="projectVersion"></param>
        public void ModifyProjectName(string projectName)
        {
            if (CurrentProject != null)
            {
                this.CurrentProject.Name = projectName;
                this.CurrentProject.DisplayName = projectName;
                this.saveProject();
            }
        }

        /// <summary>
        /// 更改项目版本
        /// </summary>
        /// <param name="projectVersion"></param>
        public void ModifyProjectVersion(string projectVersion)
        {
            if (CurrentProject != null)
            {
                this.CurrentProject.ProjectVersion = projectVersion;
                this.saveProject();
            }
        }

        /// <summary>
        /// 更改项目描述
        /// </summary>
        /// <param name="description"></param>
        public void ModifyProjectDescription(string description)
        {
            if (CurrentProject != null)
            {
                this.CurrentProject.Description = description;
                this.saveProject();
            }
        }

        /// <summary>
        /// 更改项目描述
        /// </summary>
        /// <param name="description"></param>
        public void ModifyProjectId(string projectId)
        {
            if (CurrentProject != null)
            {
                this.CurrentProject.Id = projectId;
                this.saveProject();
            }
        }

        public void ModifyTargetPlatform(string platform)
        {
            if (CurrentProject != null)
            {
                this.CurrentProject.TargetPlatform = platform;
                this.saveProject();
            }
        }

        public void ModifyWFLanguage(string language)
        {
            if (CurrentProject != null)
            {
                this.CurrentProject.WFLanguage = language;
                this.saveProject();
            }
        }

        public bool ValidateScripts()
        {
            var result = true;
            if (CurrentProject != null)
            {
                var fileNode = CurrentProject.Children.FirstOrDefault(item => item.NodeType == EProjectNodeType.Folder && item.Name == StaticResource.ProjectSelfFile);
                var files = fileNode.Children.Select(item => item as ProjectFile);

                foreach (var file in files)
                {
                    var infos = XamlAnalyzerHost.Validate(file.FullName);
                    if (infos != null && infos.Count() > 0)
                    {
                        result = false;
                    }
                }
            }
            return result;
        }

        public IEnumerable<ValidationErrorInfo> ValidateScriptALL(string fullName = "")
        {
            if (CurrentProject != null)
            {
                var fileNode = CurrentProject.Children.FirstOrDefault(item => item.NodeType == EProjectNodeType.Folder && item.Name == StaticResource.ProjectSelfFile);

                IEnumerable<ProjectFile> files = null;
                if (string.IsNullOrWhiteSpace(fullName))
                {
                    files = fileNode.Children.Select(item => item as ProjectFile);
                }
                else
                {
                    files = fileNode.Children.Select(item => item as ProjectFile).Where(o => o.FullName == fullName);
                }
                List<ValidationErrorInfo> listErrprInfo = new List<ValidationErrorInfo>();
                foreach (var file in files)
                {
                    var infos = XamlAnalyzerHost.Validate(file.FullName);
                    if (infos != null && infos.Count() > 0)
                    {
                        foreach (var info in infos)
                        {
                            ValidationErrorInfo validationErrorInfo = new ValidationErrorInfo();

                            validationErrorInfo.FileName = file.DisplayName;
                            validationErrorInfo.FullName = file.FullName;
                            if (!String.IsNullOrWhiteSpace(info.Id))
                            {
                                validationErrorInfo.Id = info.Id;
                            }

                            if (!String.IsNullOrWhiteSpace(info.ActivityParentIdRef))
                            {
                                validationErrorInfo.ActivityParentIdRef = info.ActivityParentIdRef;
                            }

                            if (!String.IsNullOrWhiteSpace(info.PropertyName))
                            {
                                validationErrorInfo.PropertyName = info.PropertyName;
                            }

                            if (!String.IsNullOrWhiteSpace(info.Message))
                            {
                                validationErrorInfo.Message = info.Message;
                            }

                            if (!String.IsNullOrWhiteSpace(info.ActivityParentId))
                            {
                                validationErrorInfo.ActivityParentId = info.ActivityParentId;
                            }
                            if (!String.IsNullOrWhiteSpace(info.ActivityParentName))
                            {
                                validationErrorInfo.ActivityParentName = info.ActivityParentName;
                            }

                            validationErrorInfo.ErrorType = info.IsWarning ? "Warming" : "Error";

                            listErrprInfo.Add(validationErrorInfo);
                        }
                    }
                }
                return listErrprInfo;
            }
            else
            {
                return null;
            }
        }
        #region 获取项目文件树
        public List<ProjectTreeView> refreshTreeView()
        {
            List<ProjectTreeView> projectTreeViews = new List<ProjectTreeView>();
            var proInfo = _projectManager.CurrentProject.Children;
            if (proInfo != null)
            {
                foreach (var item in proInfo)
                {
                    if (item.NodeType == EProjectNodeType.Folder)
                    {
                        string[] filepaths = null;
                        ProjectTreeView projectTreeView = null;
                        if (FileHelper.CheckFolderExisting(item.FullName))
                        {
                            projectTreeView = new ProjectTreeView(true)
                            {
                                DisplayName = item.DisplayName,
                                Name = item.Name,
                                FullName = System.IO.Path.Combine(item.FullName, item.Name),
                                Parent = null,
                                IsExisting = true,
                                IsChecked = true,
                                IsExpanded = true,
                                FontWeight = "Bold",
                                Foreground = "#333333"
                            };
                            filepaths = FileHelper.GetAllFilesFromFolder(item.FullName);
                        }
                        else
                        {
                            continue;
                        }

                        foreach (var fullName in filepaths)
                        {
                            var displayName = System.IO.Path.GetFileName(fullName);
                            bool isSelf = false;
                            if (displayName == "main.xaml")
                            {
                                isSelf = true;
                            }
                            ProjectTreeViewItem projectTreeViewItem = new ProjectTreeViewItem(isSelf)
                            {
                                FullName = fullName,
                                Name = displayName,
                                DisplayName = displayName,
                                Parent = projectTreeView,
                                IsExisting = true,
                                IsChecked = item.Children.Where(o => o.FullName == fullName).Count() > 0,
                                FontWeight = "Normal",
                                Foreground = isSelf ? "#c0c0c0" : "#333333",
                                IsEnabled = isSelf ? false : true
                            };

                            projectTreeView.Children.Add(projectTreeViewItem);
                        }
                        projectTreeViews.Add(projectTreeView);
                    }
                }
            }
            return projectTreeViews;
        }
        #endregion

        #region 清理图片
        public List<string> ClearActivityImages(out int clearImageNum)
        {
            var projectInfo = _projectManager.GetProjectFolder(StaticResource.ProjectSelfFile);
            clearImageNum = 0;
            List<string> imagesList = new List<string>();
            List<string> imagesFullName = new List<string>();
            if (projectInfo != null)
            {
                if (projectInfo.Children.Count > 0)
                {
                    foreach (var item in projectInfo.Children)
                    {
                        var projectFile = item as ProjectFile;
                        if (projectFile.Extension != StaticResource.XamlExtension)
                            continue;
                        XDocument xDocument = XDocument.Load(projectFile.FullName);
                        IEnumerable<XElement> xElement = xDocument.Descendants();
                        foreach (XElement node in xElement)
                        {
                            var imageNames = this.getPorjectImages(node);
                            foreach (var imageName in imageNames)
                            {
                                imagesFullName.Add(imageName);
                            }
                        }
                    }
                    int clearNum;
                    imagesList = clearActivityImage(imagesFullName, out clearNum);
                    clearImageNum = clearNum;
                }
            }
            return imagesList;
        }
        private List<string> getPorjectImages(XElement xElement)
        {
            List<string> LocalName = new List<string>();
            if (xElement.Attributes().Any((XAttribute a) => a.Name.LocalName == "FileName"))
                LocalName.Add("FileName");
            if (xElement.Attributes().Any((XAttribute a) => a.Name.LocalName == "BackFileName"))
                LocalName.Add("BackFileName");
            if (xElement.Attributes().Any((XAttribute a) => a.Name.LocalName == "CaptureFile"))
                LocalName.Add("CaptureFile");
            if (xElement.Attributes().Any((XAttribute a) => a.Name.LocalName == "SaveFile"))
                LocalName.Add("SaveFile");
            if (xElement.Attributes().Any((XAttribute a) => a.Name.LocalName == "FileNameBack"))
                LocalName.Add("FileNameBack");

            if (xElement.Attributes().Any((XAttribute a) => a.Value == "Image"))
                LocalName.Add("Image");
            List<string> imageNameList = new List<string>();
            foreach (var item in LocalName)
            {
                if (item == "Image")
                {
                    if (xElement != null)
                        imageNameList.Add(System.IO.Path.GetFileName(xElement.Value));
                }
                else
                {
                    XAttribute xattribute = xElement.Attribute(item);
                    if (xattribute != null)
                        imageNameList.Add(xattribute.Value);
                }
            }

            return imageNameList;
        }
        private List<string> clearActivityImage(List<string> imagesFullName, out int clearNum)
        {
            clearNum = 0;
            var projectInfo = GetProjectFolder(StaticResource.ProjectSelfImages);
            var fileimages = Directory.GetFiles(projectInfo.FullName);
            List<string> imagesList = new List<string>();
            foreach (var fileimage in fileimages)
            {
                var imagefile = Path.GetFileName(fileimage);
                if (imagesFullName.Where(o => o == imagefile).Count() == 0)
                {
                    try
                    {
                        FileHelper.DeleteFile(fileimage);
                    }
                    catch (Exception)
                    {
                        continue;
                    }

                    clearNum++;
                }
                else
                {
                    imagesList.Add(imagefile);
                }
            }
            return imagesList;
        }
        #endregion

        private ProjectParamDetail getParamDetail(string projectPath)
        {
            var detailPath = System.IO.Path.Combine(projectPath, StaticResource.ProjectParams);

            ProjectParamDetail detail = null;

            if (FileHelper.CheckFileExisting(detailPath))//检查配置文件是否存在，如果存在这加载，否者新建。
            {
                detail = YamlHelper.Load<ProjectParamDetail>(detailPath, true);
            }

            if (detail == null)
            {
                detail = new ProjectParamDetail()
                {
                    Input = new List<Models.ProjectParam>(), 
                    Output = new List<Models.ProjectParam>()
                };
            }

            return detail;
        }
    }
}

